package com.example.project22_editingmediaplayer.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;

import com.example.minimusicdemo.Fragment_playmain;
import com.example.minimusicdemo.Main_play;
import com.example.project22_editingmediaplayer.LayoutAllSong;
import com.example.project22_editingmediaplayer.MainActivity;
import com.example.project22_editingmediaplayer.R;
import com.example.project22_editingmediaplayer.objects.SongObject;
import com.example.project22_editingmediaplayer.resource.SongResource;

public class MediaService extends Service implements OnCompletionListener {
	public static String NOTIFICATION = "com.example.project22_editingmediaplayer";
	private ArrayList<SongObject> listSong;
	private final IBinder mMediaBinder = new LocalMediaBinder();
	private MediaPlayer mediaPlayer;
	private int index = 0;
	private int lastindex;
	private boolean isRepeat = false;
	private boolean isShuffle = false;
	public static boolean flag_first = true;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mMediaBinder;
	}

	public void setShuffle(boolean isShuffle) {
		this.isShuffle = isShuffle;
	}
	 @Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		 if(intent.getAction().equals(MainActivity.GET_INDEX)){
			 Intent i = new Intent();
				i.setAction(MainActivity.GET_INDEX);
				i.putExtra("index", getIndex());
				sendBroadcast(i);
		 }
		return super.onStartCommand(intent, flags, startId);
	}
	public boolean isShuffle() {
		return isShuffle;
	}

	public boolean isRepeat() {
		return isRepeat;
	}
	/*public boolean getisflagfirst() {
		return flag_first;
	}*/
	public SongObject getsong() {
		return listSong.get(index);
	}

	public void setRepeat(boolean isRepeat) {
		this.isRepeat = isRepeat;
	}
	/*public void setflagfirst(boolean isRepeat) {
		this.flag_first = isRepeat;
	}*/
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		return super.onUnbind(intent);
	}

	public class LocalMediaBinder extends Binder {
		public MediaService getMediaService() {
			return MediaService.this;
		}
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		lastindex = index;
		if (isRepeat) {
			PlaySong(index);
		} else if (isShuffle) {
			Random rand = new Random();
			int currentSongIndex = rand.nextInt(listSong.size());
			PlaySong(currentSongIndex);
		} else {
			try {
				if (listSong != null) {
					if (index < listSong.size() - 1) {
						index++;
						PlaySong(index);
					} else {
						index = 0;
						PlaySong(index);
					}
				} else {
					listSong = SongResource.listSong;

					PlaySong(index);
					flag_first = true;
					Log.e("tuyenpx", "listsong null");
				}

			} catch (Exception e) {
				Log.e("tuyenpx", "van con thang khac null");
			}
		}
		Intent intent = new Intent(NOTIFICATION);
		intent.putExtra("index", getIndex());
		intent.putExtra("lastindext", getlastIndex());
		// send broad cast when complete play audio and show noti
		sendBroadcast(intent);
		showNotification(index, listSong.get(index));
	}

	public MediaPlayer getMediaPlayer() {
		return this.mediaPlayer;
	}

	public void PlaySong(int indexSong) {
	//	lastindex = index;
		listSong = SongResource.listSong;
		this.index = indexSong;
		mediaPlayer.reset();
		try {
			mediaPlayer.reset();
			mediaPlayer.setDataSource(listSong.get(indexSong).get_path());
			mediaPlayer.prepare();
			mediaPlayer.start();
			Log.e("rating", "chay");
			SongResource.listSong.get(indexSong).set_rating(SongResource.listSong.get(indexSong).get_rating()+1);
			Intent intentoDatabaseService = new Intent();
			intentoDatabaseService.setAction(MainActivity.UPDATE_SONG);
			intentoDatabaseService.putExtra("songUpdate", SongResource.listSong.get(indexSong));
			startService(intentoDatabaseService);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) { // TODO Auto-generated catch block
			e.printStackTrace();
		}
		Intent intent = new Intent(NOTIFICATION);
		intent.putExtra("index", getIndex());
		intent.putExtra("lastindext", getlastIndex());
		// send broad cast when complete play audio and show noti
		sendBroadcast(intent);
		showNotification(index, listSong.get(index));
	}

	public int getIndex() {
		return this.index;
	}

	public int getlastIndex() {
		return this.lastindex;
	}

	public void nextSong() {
		lastindex = index;
		if (index < listSong.size() - 1) {
			index++;
			PlaySong(index);
		} else {
			index = 0;
			PlaySong(index);
		}
		showNotification(index, listSong.get(index));
	}

	public void nextSong(boolean noti) {
	//	lastindex = index;
		if (index < listSong.size() - 1) {
			index++;
			PlaySong(index);
		} else {
			index = 0;
			PlaySong(index);
		}
		Intent intent = new Intent(NOTIFICATION);
		intent.putExtra("index", getIndex());
		intent.putExtra("lastindext", getlastIndex());
		// send broad cast when complete play audio and show noti
		sendBroadcast(intent);
		showNotification(index, listSong.get(index));
		
	}

	/**
	 * method previus song
	 */
	public void previusSong() {
		lastindex = index;
		if (index > 0) {
			index--;
			PlaySong(index);
		} else {
//			index = listSong.size() - 1;
//			PlaySong(index);
			
		}
		Intent intent = new Intent(NOTIFICATION);
		intent.putExtra("index", getIndex());
		intent.putExtra("lastindext", getlastIndex());
		// send broad cast when complete play audio and show noti
		sendBroadcast(intent);
		showNotification(index, listSong.get(index));
	}

	public void previusSong(boolean noti) {
	//	lastindex = index;
		if (index > 0) {
			index--;
			PlaySong(index);
		} else {
			index = listSong.size() - 1;
			PlaySong(index);
		}
		showNotification(index, listSong.get(index));
	}

	public void showNotification(int index, SongObject songObject) {
		RemoteViews remoteViews = new RemoteViews(getPackageName(),
				R.layout.notification_custum);
		String strtitle = songObject.get_name();
		String strtext = songObject.get_artist();
		Intent intent = new Intent(this, Main_play.class);
		intent.putExtra("service", true);
		intent.putExtra("index", getIndex());

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		stackBuilder.addParentStack(MainActivity.class);
		stackBuilder.addNextIntent(intent);

		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		// event click play
		Intent intenPlay = new Intent(this, MediaReceiver.class);
		intenPlay.putExtra("action", "play");
		PendingIntent pendingIntentPlay = PendingIntent.getBroadcast(
				this.getApplicationContext(), 100, intenPlay, 0);
		remoteViews
				.setOnClickPendingIntent(R.id.btnPlayNoti, pendingIntentPlay);

		Intent intenNext = new Intent(this, MediaReceiver.class);
		intenNext.putExtra("action", "next");
		PendingIntent pendingIntentNext = PendingIntent.getBroadcast(
				this.getApplicationContext(), 200, intenNext, 0);
		remoteViews
				.setOnClickPendingIntent(R.id.btnNextNoti, pendingIntentNext);

		Intent intenPrevius = new Intent(this, MediaReceiver.class);
		intenPrevius.putExtra("action", "previus");
		PendingIntent pendingIntentPrevius = PendingIntent.getBroadcast(
				this.getApplicationContext(), 300, intenPrevius, 0);
		remoteViews.setOnClickPendingIntent(R.id.btnPreviousNoti,
				pendingIntentPrevius);

		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.icon)
				.setTicker(songObject.get_name()).setAutoCancel(true)
				.setContentIntent(pIntent).setContent(remoteViews);

		remoteViews.setTextViewText(R.id.txtNameNoti, strtitle);
		remoteViews.setTextViewText(R.id.txtArtisNoti, strtext);
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationmanager.notify(0, builder.build());
	}

	/**
	 * call to hide all notification
	 */
	public void hideNotification() {
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationmanager.cancel(0);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mediaPlayer.release();
	}
	
	public ArrayList<SongObject> getlistsong(){
		return listSong;
	}
	public void setlistsong( ArrayList<SongObject> i ){
		this.listSong = i;
	}

}
